<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="费用单号" prop="recordCode">
        <el-input
          v-model="queryParams.recordCode"
          placeholder="请输入费用单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="费用总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入费用总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="费用发生日期" prop="feeDate">
        <el-date-picker clearable
          v-model="queryParams.feeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择费用发生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.fee_record_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="auditBy">
        <el-input
          v-model="queryParams.auditBy"
          placeholder="请输入审核人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核时间" prop="auditTime">
        <el-date-picker clearable
          v-model="queryParams.auditTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择审核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="费用记录ID" align="center" prop="recordId" />
      <el-table-column label="费用单号" align="center" prop="recordCode" />
      <el-table-column label="费用明细" align="center">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            width="600"
            trigger="click">
            <el-table :data="JSON.parse(scope.row.feeDetails).details" border>
              <el-table-column label="费用类型" prop="typeName" align="center" />
              <el-table-column label="所属部门" prop="deptId" align="center">
                <template slot-scope="scope">
                  <span>{{ deptMap[scope.row.deptId] || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="金额" prop="amount" align="center">
                <template slot-scope="scope">
                  {{ scope.row.amount.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip />
            </el-table>
            <el-button slot="reference" type="text" icon="el-icon-view">
              查看明细 ({{ JSON.parse(scope.row.feeDetails).details.length }}项)
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="费用总金额" align="center">
        <template slot-scope="scope">
          <span class="amount">{{ scope.row.totalAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费用发生日期" align="center" prop="feeDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.feeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费用说明" align="center" prop="feeDescription" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fee_record_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="auditBy" />
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核备注" align="center" prop="auditRemark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="费用单号" prop="recordCode">
          <el-input v-model="form.recordCode" placeholder="请输入费用单号" />
        </el-form-item>
        <el-form-item label="费用发生日期" prop="feeDate">
          <el-date-picker
            v-model="form.feeDate"
            type="date"
            placeholder="选择费用发生日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="费用明细">
          <div class="fee-details-form">
            <div v-for="(detail, index) in form.feeDetailsList" :key="index" class="fee-detail-item">
              <div class="detail-header">
                <span class="detail-title">费用项 #{{index + 1}}</span>
                <el-button type="text" icon="el-icon-delete" @click="removeFeeDetail(index)" class="delete-btn">删除</el-button>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item 
                    :label="'费用类型'"
                    :prop="'feeDetailsList.' + index + '.typeName'"
                    :rules="{
                      required: true,
                      message: '费用类型不能为空',
                      trigger: 'blur'
                    }">
                    <el-input v-model="detail.typeName" placeholder="请输入费用类型" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    :label="'所属部门'"
                    :prop="'feeDetailsList.' + index + '.deptId'"
                    :rules="{
                      required: true,
                      message: '所属部门不能为空',
                      trigger: 'change'
                    }">
                    <el-cascader
                      v-model="detail.deptId"
                      :options="deptOptions"
                      :props="{
                        checkStrictly: true,
                        value: 'deptId',
                        label: 'deptName',
                        children: 'children',
                        leaf: 'leaf',
                        emitPath: false,
                        expandTrigger: 'hover'
                      }"
                      :show-all-levels="true"
                      clearable
                      placeholder="请选择所属部门"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item
                    :label="'金额'"
                    :prop="'feeDetailsList.' + index + '.amount'"
                    :rules="[
                      { required: true, message: '金额不能为空', trigger: 'blur' },
                      { type: 'number', message: '金额必须为数字', trigger: 'blur' },
                      { type: 'number', min: 0, message: '金额不能小于0', trigger: 'blur' }
                    ]">
                    <el-input-number 
                      v-model="detail.amount" 
                      :precision="2"
                      :step="100"
                      :min="0"
                      placeholder="请输入金额"
                      @change="calculateTotal"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    :label="'备注'"
                    :prop="'feeDetailsList.' + index + '.remark'"
                    :rules="{
                      required: true,
                      message: '备注不能为空',
                      trigger: 'blur'
                    }">
                    <el-input v-model="detail.remark" placeholder="请输入备注说明" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div class="add-detail-btn">
              <el-button type="primary" icon="el-icon-plus" @click="addFeeDetail">添加费用明细</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="费用总额" prop="totalAmount">
          <el-input-number
            v-model="form.totalAmount"
            :disabled="true"
            :precision="2"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="费用说明" prop="feeDescription">
          <el-input v-model="form.feeDescription" type="textarea" placeholder="请输入费用说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/system/record";
import { listDept } from "@/api/system/dept";

export default {
  name: "Record",
  dicts: ['fee_record_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门数据缓存
      deptMap: {},
      // 部门选项列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recordCode: null,
        totalAmount: null,
        feeDate: null,
        status: null,
        auditBy: null,
        auditTime: null
      },
      // 表单参数
      form: {
        recordId: null,
        recordCode: null,
        feeDetailsList: [],
        totalAmount: 0,
        feeDate: null,
        feeDescription: null,
        status: "0",
        auditBy: null,
        auditTime: null,
        auditRemark: null
      },
      // 表单校验
      rules: {
        recordCode: [
          { required: true, message: "费用单号不能为空", trigger: "blur" }
        ],
        feeDate: [
          { required: true, message: "费用发生日期不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "费用总额不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "费用总额不能小于0", trigger: "blur" }
        ],
        feeDetailsList: [
          { required: true, message: "请至少添加一条费用明细", trigger: "change" }
        ]
      }
    };
  },
  created() {
    // 先加载部门数据，再加载列表
    this.initDeptData().then(() => {
      this.getList();
    });
  },
  methods: {
    /** 初始化部门数据 */
    initDeptData() {
      return new Promise((resolve, reject) => {
        listDept().then(response => {
          if (response.code === 200) {
            // 构建部门ID到名称的映射
            const deptMap = {};
            response.data.forEach(dept => {
              deptMap[dept.deptId] = dept;
            });
            
            // 构建完整的部门路径映射
            this.deptMap = {};
            response.data.forEach(dept => {
              const ancestors = dept.ancestors.split(',').filter(id => id !== '0');
              const path = ancestors.map(id => deptMap[id]?.deptName || '').concat(dept.deptName);
              this.deptMap[dept.deptId] = path.join('/');
            });

            // 构建树形结构
            const buildTree = (data) => {
              const tree = [];
              const map = {};
              const childrenMap = {};
              
              data.forEach(item => {
                if (item.parentId !== 0) {
                  childrenMap[item.parentId] = (childrenMap[item.parentId] || 0) + 1;
                }
              });
              
              data.forEach(item => {
                const node = {
                  ...item,
                  leaf: !childrenMap[item.deptId]
                };
                if (childrenMap[item.deptId]) {
                  node.children = [];
                }
                map[item.deptId] = node;
              });
              
              data.forEach(item => {
                const node = map[item.deptId];
                if (item.parentId === 0) {
                  tree.push(node);
                } else {
                  const parentNode = map[item.parentId];
                  if (parentNode && parentNode.children) {
                    parentNode.children.push(node);
                  }
                }
              });
              
              return tree;
            };
            
            this.deptOptions = buildTree(response.data);
            resolve();
          } else {
            this.$modal.msgError("获取部门数据失败");
            reject();
          }
        }).catch(error => {
          console.error("获取部门数据失败:", error);
          this.$modal.msgError("获取部门数据失败");
          reject(error);
        });
      });
    },
    /** 查询费用记录列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取部门名称 */
    getDeptName(deptId) {
      return this.deptMap[deptId] || deptId;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        recordCode: null,
        feeDetailsList: [],
        totalAmount: 0,
        feeDate: null,
        feeDescription: null,
        status: "0",
        auditBy: null,
        auditTime: null,
        auditRemark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 确保有部门数据
      if (this.deptOptions.length === 0) {
        this.initDeptData().then(() => {
          this.open = true;
          this.title = "添加费用记录";
        });
      } else {
        this.open = true;
        this.title = "添加费用记录";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids;
      // 确保有部门数据
      if (this.deptOptions.length === 0) {
        this.initDeptData().then(() => {
          getRecord(recordId).then(response => {
            this.form = response.data;
            if (this.form.feeDetails) {
              try {
                const feeDetails = JSON.parse(this.form.feeDetails);
                this.form.feeDetailsList = feeDetails.details || [];  
              } catch (e) {
                this.form.feeDetailsList = [];
              }
            }
            this.open = true;
            this.title = "修改费用记录";
          });
        });
      } else {
        getRecord(recordId).then(response => {
          this.form = response.data;
          if (this.form.feeDetails) {
            try {
              const feeDetails = JSON.parse(this.form.feeDetails);
              this.form.feeDetailsList = feeDetails.details || [];  
            } catch (e) {
              this.form.feeDetailsList = [];
            }
          }
          this.open = true;
          this.title = "修改费用记录";
        });
      }
    },
    // 添加费用明细
    addFeeDetail() {
      this.form.feeDetailsList.push({
        typeName: '',
        deptId: null,
        amount: 0,
        remark: ''
      });
    },
    // 移除费用明细
    removeFeeDetail(index) {
      this.form.feeDetailsList.splice(index, 1);
      this.calculateTotal();
    },
    // 计算总金额
    calculateTotal() {
      this.form.totalAmount = this.form.feeDetailsList.reduce((sum, detail) => sum + (detail.amount || 0), 0);
    },
    /** 提交按钮 */
    submitForm() {
      // 手动验证费用明细
      let isValid = true;
      if (this.form.feeDetailsList.length === 0) {
        this.$modal.msgError("请至少添加一条费用明细");
        isValid = false;
        return;
      }
      
      // 验证每个费用明细
      this.form.feeDetailsList.forEach((detail, index) => {
        if (!detail.typeName) {
          this.$modal.msgError(`第${index + 1}条费用明细的费用类型不能为空`);
          isValid = false;
        }
        if (!detail.deptId) {
          this.$modal.msgError(`第${index + 1}条费用明细的所属部门不能为空`);
          isValid = false;
        }
        if (!detail.amount && detail.amount !== 0) {
          this.$modal.msgError(`第${index + 1}条费用明细的金额不能为空`);
          isValid = false;
        }
      });

      if (!isValid) {
        return;
      }

      // 验证基本表单
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 更新feeDetails字段
          this.form.feeDetails = JSON.stringify({
            details: this.form.feeDetailsList
          });
          
          if (this.form.recordId != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除费用记录编号为"' + recordIds + '"的数据项？').then(function() {
        return delRecord(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.fee-details-form {
  margin-bottom: 10px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.fee-detail-item {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-title {
  font-weight: bold;
  color: #606266;
}

.delete-btn {
  padding: 0;
  color: #f56c6c;
}

.add-detail-btn {
  text-align: center;
  margin-top: 10px;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

.amount {
  color: #67C23A;
  font-weight: bold;
}
.el-table {
  margin: 0;
  width: 100%;
}
.el-popover {
  max-width: 80vw;
}
</style>
